package yadong.demo.wifichecker;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiManager;

public class ServiceMain extends IntentService {
	private static final String ADDRESS = "192.168.1.108";
	private static final String HOST_MAC = "28:2c:b2:9f:6b:c2";
	private static final String SHARED_PREFRENCE = "wifi.saver";
	private static final String EXTRA_KAY_NAME = "extras_key";

	private static final String REQUEST_EXIT = "re_exit";
	private static final String REQUEST_KEY = "rq_request_key";
	private static final String REQUEST_CHECK_PREFIX = "rq_check_key_";
	private static final String RESPONSE_KEY_PREX = "rp_key_";
	private static final String REQUEST_CODE_KEY_ERROR = "key_err";

	private static final int PORT = 8821;

	private Socket mSocket;
	private SharedPreferences mKeySaverPreference;

	public ServiceMain(String name) {
		super(name);
	}

	public ServiceMain() {
		super("services");
	}

	private WifiManager manager;

	@Override
	protected void onHandleIntent(Intent intent) {
		manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		mKeySaverPreference = ServiceMain.this.getSharedPreferences(
				SHARED_PREFRENCE, MODE_PRIVATE);
		Logger.v(this, "bssid=" + manager.getConnectionInfo().getBSSID());
		Logger.v(this, "mac=" + manager.getConnectionInfo().getMacAddress());
		Logger.v(this, "name=" + manager.getConnectionInfo().getSSID());
		// If the WIFI host mac is my home's mac send a message to Server and
		// get Identity
		if (HOST_MAC.equals(manager.getConnectionInfo().getBSSID())) {
			Logger.d(ServiceMain.this, "connet to right host");
			new Thread(createTask()).start();
		}
	}

	// Create the socket connection runnable.
	private Runnable createTask() {
		return new Runnable() {
			public void run() {
				try {
					mSocket = new Socket(ADDRESS, PORT);
					new Thread(createListen()).start();
					BufferedWriter bw = new BufferedWriter(
							new OutputStreamWriter(mSocket.getOutputStream()));
					// Get the private key from shared preference.
					String privateKey = mKeySaverPreference.getString(
							EXTRA_KAY_NAME, null);
					// If the private key is null request the key.
					if (privateKey == null) {
						bw.write(REQUEST_KEY + "\n");
					} else {
						bw.write(REQUEST_CHECK_PREFIX + privateKey + "\n");
					}
					bw.write(REQUEST_EXIT + "\n");
					bw.flush();
				} catch (IOException e) {
					e.printStackTrace();
					Logger.e(ServiceMain.this, e.getMessage());
				}
			}
		};
	}

	private Runnable createListen() {
		return new Runnable() {
			@Override
			public void run() {
				BufferedReader br = null;
				try {
					if (mSocket != null) {
						br = new BufferedReader(new InputStreamReader(
								mSocket.getInputStream()));
						String msg = null;
						while ((msg = br.readLine()) != null) {
							Logger.d(ServiceMain.this,
									"get message from server:" + msg);
							if (msg.startsWith(RESPONSE_KEY_PREX)) {
								// Get the
								String key = msg.substring(msg
										.indexOf(RESPONSE_KEY_PREX));
								writeToPreference(EXTRA_KAY_NAME, key);
							}
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
					Logger.e(ServiceMain.this, e.getMessage());
				} finally {
					if (br != null) {
						try {
							br.close();
						} catch (IOException e) {
							e.printStackTrace();
							Logger.e(ServiceMain.this, e.getMessage());
						}
					}
				}
			}
		};

	}

	// Replace the old private key with new key from server.
	private void writeToPreference(String tag, String value) {
		Editor editor = mKeySaverPreference.edit();
		editor.remove(tag);
		editor.putString(tag, value);
		editor.commit();
	}
}
